import { connect } from 'dva'

import { deleteCommodityApi, offShelvesCommodityApi, onShelvesCommodityApi } from '@/api/pcs/commodity'
import { hospitalAndAreaTreeApi } from '@/api/pcs/pcsHospital'
import AekButton from '@/components/AekButton'
import AekLinkButton from '@/components/AekLinkButton'
import AekModal from '@/components/AekModal'
import AekTable from '@/components/AekTable'
import PageLayout from '@/components/PageLayout'
import Preview from '@/components/Preview'
import SearchForm from '@/components/SearchForm'
import { namespace } from '@/models/pcs/commodity'
import { getPagination, message, modal } from '@/utils/antdHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'
import { FILE_TYPE_ENUM, PCS_GOODS_STATUS_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import EditModal from './components/EditModal'

/** 陪护 - 商品管理 */
const Index = ({ modelState, loading }) => {
  const { pageList, pagination, searchParams } = modelState
  const { toAction, getLoading } = getBasicFn({ namespace, loading })

  const getHospitalAndAreaTree = async () => {
    const _hospitalAndAreaTree = []
    const { data } = await requestWithTry(hospitalAndAreaTreeApi)
    data.forEach(item => {
      const { areaInfos } = item
      areaInfos.forEach(childItem => {
        _hospitalAndAreaTree.push({
          id: childItem.id,
          name: `${item.name}/${childItem.name}`,
        })
      })
    })
    return { data: _hospitalAndAreaTree }
  }

  const add = async () => {
    await EditModal.PromiseThen()
    message.success('新增成功')
    toAction('getPageList')
  }

  const edit = async row => {
    await EditModal.PromiseThen({
      row,
    })
    message.success('修改成功')
    toAction('getPageList')
  }

  const remove = async ({ id, commodityName }) => {
    modal.confirm({
      title: '删除',
      content: `确认删除商品【${commodityName}】？`,
      onOk: async () => {
        await requestWithTry(deleteCommodityApi, { id })
        message.success('删除成功')
        if ((pagination.current - 1) * pagination.pageSize === pagination.total - 1) {
          toAction('getPageList', { current: pagination.current - 1 || 1 })
        } else {
          toAction('getPageList')
        }
      },
    })
  }

  const onShelves = async ({ id, commodityName }) => {
    modal.confirm({
      title: '上架',
      content: `确认上架商品【${commodityName}】？`,
      onOk: async () => {
        await requestWithTry(onShelvesCommodityApi, { id })
        message.success('上架成功')
        toAction('getPageList')
      },
    })
  }

  const offShelves = async ({ id, commodityName }) => {
    modal.confirm({
      title: '下架',
      content: `确认下架商品【${commodityName}】？`,
      onOk: async () => {
        await requestWithTry(offShelvesCommodityApi, { id })
        message.success('下架成功')
        toAction('getPageList')
      },
    })
  }

  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'status',
        label: '状态',
        component: {
          name: 'Select',
          props: {
            options: PCS_GOODS_STATUS_ENUM.options,
            defaultValue: PCS_GOODS_STATUS_ENUM.ALL,
          },
        },
      },
      {
        field: 'hospitalId',
        label: '医院',
        component: {
          name: 'AekSelect',
          props: {
            api: getHospitalAndAreaTree,
          },
        },
      },
      {
        field: 'commodityName',
        label: '商品名称',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'commodityModel',
        label: '规格型号',
        component: {
          name: 'Input',
        },
      },
    ],
    onSearch: values => {
      toAction({ searchParams: values })
      toAction({ pagination: { current: 1 } }, true)
      toAction('getPageList')
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: namespace,
    rowKey: 'id',
    loading: getLoading('getPageList'),
    dataSource: pageList,
    pagination: getPagination(pagination, (current, pageSize) => {
      toAction('getPageList', { current, pageSize })
    }),
    columns: [
      { dataIndex: 'status', title: '状态', enum: PCS_GOODS_STATUS_ENUM },
      {
        dataIndex: 'commodityImage',
        title: '商品主图',
        render: fileUrl => {
          return (
            <img
              alt='商品主图'
              src={fileUrl}
              className='mx-auto block size-16 rounded-md'
              onClick={() =>
                Preview.PromiseThen({
                  previewIndex: 0,
                  previewList: [
                    {
                      type: FILE_TYPE_ENUM.IMAGE,
                      url: fileUrl,
                    },
                  ],
                })
              }
            />
          )
        },
      },
      { dataIndex: 'commodityName', title: '商品名称' },
      { dataIndex: 'commodityModel', title: '规格型号' },
      { dataIndex: 'brand', title: '品牌' },
      { dataIndex: 'manufacturer', title: '厂家' },
      { dataIndex: 'unit', title: '单位' },
      { dataIndex: 'price', title: '单价', isMoney: true },
      {
        dataIndex: 'addressDetail',
        title: '居家',
        render: (_text, row) =>
          row.homeDelivery ? (
            <AekLinkButton
              onClick={() => {
                AekModal.PromiseThen({
                  title: '居家',
                  showFooter: false,
                  children: (
                    <div>
                      {row.addressDetail.map(name => (
                        <div key={name} className='text-16px'>
                          {name}
                        </div>
                      ))}
                    </div>
                  ),
                })
              }}
            >
              {row.addressDetail.length}
            </AekLinkButton>
          ) : (
            0
          ),
      },
      {
        dataIndex: 'hospitalDetail',
        title: '医院',
        render: (_text, row) =>
          row.hospitalDelivery ? (
            <AekLinkButton
              onClick={() => {
                AekModal.PromiseThen({
                  title: '医院',
                  showFooter: false,
                  children: (
                    <div>
                      {row.hospitalDetail.map(name => (
                        <div key={name} className='text-16px'>
                          {name}
                        </div>
                      ))}
                    </div>
                  ),
                })
              }}
            >
              {row.hospitalDetail.length}
            </AekLinkButton>
          ) : (
            0
          ),
      },
      { dataIndex: 'createUserName', title: '创建人' },
      { dataIndex: 'createTime', title: '创建时间', isDateTime: true },
      {
        key: 'operate',
        title: '操作',
        fixed: 'right',
        width: 150,
        className: 'text-center!',
        render: (_, row) =>
          row.status === PCS_GOODS_STATUS_ENUM.HAS_LISTED ? (
            <AekLinkButton danger onClick={() => offShelves(row)}>
              下架
            </AekLinkButton>
          ) : (
            <>
              <AekLinkButton danger onClick={() => onShelves(row)}>
                上架
              </AekLinkButton>
              <AekLinkButton onClick={() => edit(row)}>编辑</AekLinkButton>
              <AekLinkButton danger onClick={() => remove(row)}>
                删除
              </AekLinkButton>
            </>
          ),
      },
    ],
  }

  return (
    <PageLayout
      extraSuffix={
        <AekButton type='primary' onClick={add}>
          新建
        </AekButton>
      }
    >
      <SearchForm {...searchProps} />
      <AekTable {...tableProps} />
    </PageLayout>
  )
}

export default connect(store => ({
  modelState: store[namespace],
  loading: store.loading,
}))(Index)
